<?php

namespace app\service;

use app\model\Card;
use app\model\ExploreAddress;
use app\model\ExploreChapter;
use app\model\ExploreNavigation;
use app\model\ExploreStory;
use app\model\ExploreTask;
use app\model\ExploreTaskReward;
use app\model\Factory;
use app\model\Fish;
use app\model\Skin;
use app\model\UserExploreTask;
use app\model\UserIngredient;
use app\model\UserStaff;
use plugin\admin\app\model\Staff;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserExploreService extends BaseService
{


    /**
     * 获取探索星球
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_explore_address_list($user_id): array
    {
        $explore_address_list = (new ExploreAddress())->with('chapter')->select()->toArray();
        $explore_task_ids = UserExploreTask::where('user_id', $user_id)->column('explore_task_id');
        $story_list = (new ExploreStory())->with('task')->select()->toArray();

        $next_address_id = 1;
        foreach ($explore_address_list as $key => &$explore_address) {
            $explore_address['unlock'] = 0;
            $explore_address['complete'] = 0;

            $list = [];
            //章节下面的所有故事
            $chapter_ids = array_column($explore_address['chapter'], 'id');
            foreach ($story_list as $story) {
                if (in_array($story['explore_chapter_id'], $chapter_ids)) {
                    $list[] = $story;
                }
            }

            $explore_chapter_list = $this->get_explore_calculation($list, $explore_task_ids);
            $complete = array_column($explore_chapter_list, 'complete');
            $unlock = array_column($explore_chapter_list, 'unlock');
            if ($next_address_id > $key) {
                $explore_address['unlock'] = 1;
            }

            if (count(array_unique($unlock)) === 1 && in_array(1, $unlock)) {
                $explore_address['unlock'] = 1;
            }

            if (count(array_unique($complete)) === 1 && in_array(1, $complete)) {
                $explore_address['complete'] = 1;
            }
            //删除
            unset($explore_address['chapter']);
        }


        return $this->returnSuccess($explore_address_list);
    }


    /**
     * 获取探索章节
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_explore_chapter_list($user_id, $explore_address_id): array
    {
        $explore_chapter_list = (new ExploreChapter())->where('explore_address_id', $explore_address_id)->select()->toArray();
        $explore_task_ids = UserExploreTask::where('user_id', $user_id)->column('explore_task_id');
        $story_list = (new ExploreStory())->with('task')->select()->toArray();


        $next_address_id = 1;
        foreach ($explore_chapter_list as $key => &$explore_chapter) {
            $explore_chapter['unlock'] = 0;
            $explore_chapter['complete'] = 0;

            $list = [];
            foreach ($story_list as $story) {
               if ($story['explore_chapter_id'] == $explore_chapter['id']) {
                   $list[] = $story;
               }
            }

            $explore_story_list = $this->get_explore_calculation($list, $explore_task_ids);
            $complete = array_column($explore_story_list, 'complete');
            $unlock = array_column($explore_story_list, 'unlock');
            if ($next_address_id > $key) {
                $explore_chapter['unlock'] = 1;
            }

            if (count(array_unique($unlock)) === 1 && in_array(1, $unlock)) {
                $explore_chapter['unlock'] = 1;
            }

            if (count(array_unique($complete)) === 1 && in_array(1, $complete)) {
                $explore_chapter['complete'] = 1;
            }
            //删除
            unset($explore_chapter['story']);
        }


        return $this->returnSuccess($explore_chapter_list);

    }


    /**
     * 获取探索章节
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_explore_story_list($user_id, $explore_chapter_id): array
    {
        $explore_story_list = (new ExploreStory())->with('task')->where('explore_chapter_id', $explore_chapter_id)->select()->toArray();
        $user_explore_task = (new UserExploreTask())->where('user_id', $user_id)->find();
        $explore_task_ids = UserExploreTask::where('user_id', $user_id)->column('explore_task_id');

        $explore_story_list = $this->get_explore_calculation($explore_story_list, $explore_task_ids);


        return $this->returnSuccess($explore_story_list);

    }


    /**
     * 获取探索任务
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_explore_task_list($user_id, $explore_story_id): array
    {
        $explore_task_list = (new ExploreTask())->where('explore_story_id', $explore_story_id)->select();
        $explore_task_ids = UserExploreTask::where('user_id', $user_id)->column('explore_task_id');
        foreach ($explore_task_list as &$explore_task) {
            $explore_task->props = json_decode($explore_task->props, true);
            $explore_task->complete = 0;
            if ($explore_task_ids) {
                if (in_array($explore_task->id, $explore_task_ids)) {
                    $explore_task->complete = 1;
                }
            }

        }
        return $this->returnSuccess($explore_task_list);
    }

    /**
     * 获取探索导航-收录任务
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_explore_navigation_list($user_id, $explore_address_id): array
    {
        $explore_task_list = (new ExploreNavigation())->where('explore_address_id', $explore_address_id)->select()->toArray();

        $list = [];
        //导航类型 1=角色 2=服装 3=建筑 4=卡牌 5=鱼类
        foreach ($explore_task_list as $item) {
            if ($item['type'] == EXPLORE_NAV_TYPE['角色']){
                //角色详情
                $item['info'] = (new Staff())->find($item['pid']);
                //用户是否已经拥有
                $item['own'] = (new UserStaff())->where('user_id', $user_id)->where('staff_id', $item['pid'])->find() ? 1 : 0;


                $list['role'][] = $item;
            }
            if ($item['type'] == EXPLORE_NAV_TYPE['服装']){
                //服装详情
                $item['info'] = (new Skin())->find($item['pid']);
                $list['cos'][] = $item;
            }
            if ($item['type'] == EXPLORE_NAV_TYPE['建筑']){
                //建筑详情
                $item['info'] = (new Factory())->find($item['pid']);
                $list['building'][] = $item;
            }
            if ($item['type'] == EXPLORE_NAV_TYPE['卡牌']){
                //卡牌详情
                $item['info'] = (new Card())->find($item['pid']);
                $list['card'][] = $item;
            }
            if ($item['type'] == EXPLORE_NAV_TYPE['鱼类']){
                //鱼类详情
                $item['info'] = (new Fish())->find($item['pid']);
                $list['fish'][] = $item;
            }
        }
        
        return $this->returnSuccess($list);
    }



    /**
     * 提交工具
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function submit_tool($user_id, $explore_task_id): array
    {
        //查询该任务需要的工具
        $explore_task =  ExploreTask::where('id', $explore_task_id)->find();
        if (!$explore_task) {
            return $this->returnFail('任务不存在');
        }

        //所属故事
        $explore_story = ExploreStory::where('id', $explore_task->explore_story_id)->find();
        if (!$explore_story) {
            return $this->returnFail('故事不存在');
        }

        //所属章节
        $explore_chapter = ExploreChapter::where('id', $explore_story->explore_chapter_id)->find();
        if (!$explore_chapter) {
            return $this->returnFail('章节不存在');
        }
        //所属星球
        $explore_address = ExploreAddress::where('id', $explore_chapter->explore_address_id)->find();
        if (!$explore_address) {
            return $this->returnFail('星球不存在');
        }


        $explore_task->props = json_decode($explore_task->props, true);

        //需要的工具
        foreach ($explore_task->props as $prop) {
            $id = $prop['id'];
            $num = $prop['num'];
            //加材料--用于测试
           /* (new UserIngredient())->save([
                'user_id' => $user_id,
                'ingredients_id' => $id,
                'num' => $num * 1000,
            ]);*/


            $ingredient_num = (new UserIngredient())->where('user_id', $user_id)->where('ingredients_id', $id)->value('num');
            if ($ingredient_num < $num) {
                return $this->returnFail('材料不足');
            }
        }
        //任务奖励
        $explore_task_reward_ids =  (new ExploreTaskReward())->where('explore_task_id', $explore_task_id)->column('id') ?? [];



        //判断任务是否已经提交
        $explore_task_ids = UserExploreTask::where('user_id', $user_id)->column('explore_task_id');
        if (in_array($explore_task_id, $explore_task_ids)) {
            return $this->returnFail('任务已提交');
        }
        $user_explore_task = new UserExploreTask();
        $user_explore_task->user_id = $user_id;
        $user_explore_task->explore_task_id = $explore_task_id;
        $user_explore_task->explore_address_id = $explore_address->id;
        $user_explore_task->explore_chapter_id = $explore_chapter->id;
        $user_explore_task->explore_story_id = $explore_story->id;

        if ($explore_task_reward_ids) {
            $user_explore_task->explore_reward_ids = json_encode($explore_task_reward_ids);
        }

        $user_explore_task->save();
        return $this->returnSuccess();
    }


    //查询玩家任务奖励
    public function get_user_explore_reward_list($user_id, $explore_address_id): array
    {
        //查询该星球下的所有任务
        $user_explore_task_list = UserExploreTask::where('user_id', $user_id)->where('explore_address_id', $explore_address_id)->select()->toArray();
        foreach ($user_explore_task_list as &$item) {
            $item['explore_reward_ids'] = json_decode($item['explore_reward_ids'], true);
        }
        return $this->returnSuccess($user_explore_task_list);
    }

    //领取任务奖励
    public function receive_explore_reward($user_id, $user_explore_task_id): array
    {
        //查询奖励
        $user_explore_task = UserExploreTask::where('user_id', $user_id)->where('id', $user_explore_task_id)->find();
        if (!$user_explore_task) {
            return $this->returnFail('任务不存在');
        }
        if ($user_explore_task->state == EXPLORE_REWARD_STATUS['已领取']) {
            return $this->returnFail('奖励已领取');
        }

        if ($user_explore_task->explore_reward_ids) {
            $explore_reward_ids = json_decode($user_explore_task->explore_reward_ids, true);
            $explore_reward_list = ExploreTaskReward::where('id', 'in', $explore_reward_ids)->select();
            foreach ($explore_reward_list as &$item) {
                //发放奖励

                $pid = 0;

                //判断奖励类型 $item->reward
                foreach (ITEM_RANGE as $key => $range) {
                    // 30004 是否在 [1000, 1999] 区间之间
                    if ($item->reward >= $range['range'][0] && $item->reward <= $range['range'][1]) {
                        //发放奖励
                        $pid = $key;
                        break;
                    }
                }

                if ($pid) {
                    switch ($pid) {
                        case '角色':
                            //角色奖励
                            //查询是否拥有角色
                            $has_staff = (new UserStaffService())->has_staff($user_id, $item->reward);
                            if (!$has_staff) {
                                //发放奖励
                                $res = (new UserStaffService())->add_user_staff($user_id, $item->reward);
                                if (!$res['code']) {
                                    return $this->returnFail($res);
                                }
                            } else {
                                //奖励已领取
                                return $this->returnFail('已拥有该角色 是否转化为角色碎片');
                            }
                            break;
                        case '角色皮肤':
                            //角色皮肤
                            $has_skin = (new UserSkinService())->has_skin($user_id, $item->reward);

                            if (!$has_skin) {
                                $res = (new UserSkinService())->add_user_skin($user_id, $item->reward, $item->num);
                                if (!$res['code']) {
                                    return $this->returnFail($res);
                                }
                            } else {
                                //奖励已领取
                                return $this->returnFail('已拥有该皮肤 是否转化为钻石');
                            }
                            break;
                        case '建筑装饰':
                            //建筑奖励
                            $res = (new UserOrnamentsService())->add_user_ornament($user_id, $item->reward, $item->num);
                            if (!$res['code']) {
                                return $this->returnFail($res);
                            }
                        break;
                        case '材料':
                            //建筑奖励
                            $res = (new UserIngredientsService())->add_user_ingredients($user_id, $item->reward, $item->num);
                            if (!$res['code']) {
                                return $this->returnFail($res);
                            }
                            break;
                        case '卡牌':
                            //卡牌奖励
                            $res = (new UserCardService())->add_user_card($user_id, $item->reward, $item->num);
                            if (!$res['code']) {
                                return $this->returnFail($res);
                            }
                            break;
                        case '鱼类':
                            //鱼类奖励
                            $res = (new UserFishService())->add_user_fish($user_id, $item->reward, $item->num);
                            if (!$res['code']) {
                                return $this->returnFail($res);
                            }
                            break;
                        case '角色碎片':
                            //角色碎片
                            $res = (new UserStaffFrService())->add_user_staff_fr($user_id, $item->reward, $item->num);
                            if (!$res['code']) {
                                return $this->returnFail($res);
                            }
                            break;
                        default:
                            return $this->returnFail('奖励类型错误');
                    }
                }
            }
        }
        $user_explore_task->state = EXPLORE_REWARD_STATUS['已领取'];
        $user_explore_task->save();
        return $this->returnSuccess($user_explore_task);
    }



    /**
     * @param $list
     * @param $explore_task_ids
     * @return mixed
     */
    public function get_explore_calculation($list, $explore_task_ids)
    {
        $next_chapter_id = 1;
        foreach ($list as $key => &$item) {
            $item['unlock'] = 0;
            $item['complete'] = 0;
            if ($next_chapter_id > $key) {
                $item['unlock'] = 1;
            }

            //提取ID成数组
            $task_ids_list = array_column($item['task'], 'id');
            if (count(array_diff($task_ids_list, $explore_task_ids)) === 0) {
                $next_chapter_id += 1;
                $item['complete'] = 1;
            }
            //删除task
            unset($item['task']);
        }
        return $list;
    }


}